#include "leveltransitionstate.h"
#include "levelbeginstate.h"

LevelTransitionState::LevelTransitionState(GameEngine* engine) : GameState(engine)
{
	m_server = nullptr;
	m_client = nullptr;
	m_level = nullptr;

	m_first_cycle = true;
	m_level_loaded = false;
	m_level_sent_second_time = false;
	m_shutdown_network_on_state_end = true;
}

LevelTransitionState::~LevelTransitionState()
{
	if (m_is_server)
		ServerCleanup();
	else
		ClientCleanup();

	if (m_shutdown_network_on_state_end)
	{
		delete m_level;
	}
	
	al_destroy_font(m_loading_font);
}

void LevelTransitionState::Init(bool is_server, RakNetServer* server, RakNetClient* client,
								ClientConnectionList client_list, std::string level_to_load)
{
	// Take the information from the previous state. Server and/or client might be nullpointers.
	m_is_server = is_server;
	m_server = server;
	m_client = client;

	m_client_list = client_list;
	m_level_to_load = level_to_load;

	if (m_is_server)
		ServerInit();
	else
		ClientInit();

	m_loading_font = al_load_font(STANDARD_FONT.c_str(), 50, NULL);
}

void LevelTransitionState::LoadLevel(std::string xml_data)
{
	m_level = new Level;
	LevelLoader loader(m_level);
	loader.LoadLevel(xml_data);
	m_level_loaded = true;
}

void LevelTransitionState::HandleInput(ALLEGRO_EVENT next_event)
{
}

void LevelTransitionState::Update(float timing_factor)
{
	if (m_is_server)
		ServerUpdate();
	else
		ClientUpdate();
}

void LevelTransitionState::Draw()
{
	if (m_level_loaded)
		al_draw_text(m_loading_font, al_map_rgb(255, 255, 255), 1014, 758 - al_get_font_line_height(m_loading_font), ALLEGRO_ALIGN_RIGHT, "Waiting for players...");
	else
		al_draw_text(m_loading_font, al_map_rgb(255, 255, 255), 1014, 758 - al_get_font_line_height(m_loading_font), ALLEGRO_ALIGN_RIGHT, "Loading...");
}